package server;

import java.util.ArrayList;

import util.ArrayHelpers;

import client.ClientFile;

import dataContracts.CommandParser;
import dataContracts.CommandType;

public class SynchHandler implements Runnable {
	ClientConnection client;
	ServerProgram server;
	String commandText;
	
	SynchHandler(ClientConnection client, ServerProgram server, String commandText) {
		this.server = server;
		this.client = client;
		this.commandText = commandText;
	}
	
	@Override
	public void run() {
		String clientFiles = CommandParser.getCommandText(CommandType.Synch, commandText);
		
		// keep track of changes we need to make
		ArrayList<String> added, deleted, changed;
		added = new ArrayList<String>();
		deleted = new ArrayList<String>();
		changed = new ArrayList<String>();
		
		// assume all files on server are new, and we'll remove them from the list as needed
		for (ClientFile file : server.directory.files) {
			added.add(file.getName());
		}
		
		if (!clientFiles.isEmpty()) { 
			String[] files = clientFiles.split(";");
			
			//loop through the list of files sent
			for (int i = 0; i < files.length; i++) {
				String f = files[i];
				// each file entry is in the format: filename:checksum
				String[] tmp = f.split(":");
				String name, checksum;
				if (tmp.length > 0) {
					name = tmp[0];
					checksum = tmp[1];
					
					if (server.directory.fileExists(name)) {
						added.remove(name);
						if (server.directory.fileChanged(name, checksum)) {
							changed.add(name);
							client.command(CommandParser.buildCommand(CommandType.UpdateFile, name));
						} else {
							client.command(CommandParser.buildCommand(CommandType.MarkAsCurrent, name));
						}
					} else {
						// we can't tell if it's new on client, or deleted on server... make client resolve
						client.command(CommandParser.buildCommand(CommandType.ResolveDiff, name));
						deleted.add(name);
						added.remove(name);
					}
				}
			}
		}
		
		// for all the actual new files, trigger the download
		for (String fileAdded : added) {
			client.command(CommandParser.buildCommand(CommandType.NewFile, fileAdded));
		}
		
		// build the output
		String output = ArrayHelpers.join(added, "|");
		System.out.println("New: "+ ArrayHelpers.join(added, "|"));
		output += ArrayHelpers.join(changed, "|");
		System.out.println("Changed: "+ ArrayHelpers.join(changed, "|"));
		output += ArrayHelpers.join(deleted, "|");
		System.out.println("Removed: "+ ArrayHelpers.join(deleted, "|"));
		
		String response = CommandParser.buildCommand(CommandType.Synch, output);
		client.command(response);
	}
}